package com.cold.demo.security.config;

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

@SpringBootConfiguration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    // 认证交给后台处理
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 配置用户以及用户对应的角色
        auth.inMemoryAuthentication()
                .withUser("admin1") // 管理员，同事具有 ADMIN,USER权限，可以访问所有资源
                .password("admin1")
                .roles("ADMIN", "USER")
                .and()
                .withUser("user1").password("user1") // 普通用户，只能访问 /product/**
                .roles("USER");
    }

    // 密码匹配器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new PasswordEncoder() {
            @Override
            public String encode(CharSequence rawPassword) {
                return rawPassword.toString();
            }

            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                return rawPassword.toString().equals(encodedPassword);
            }
        };
    }

    /*

     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests() // 定义哪些URL需要被保护、哪些不需要被保护
                .antMatchers("/product/**").hasRole("USER")
                .antMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated() // 除了上面的请求之外都需要进行认证
                .and()
                .formLogin() // 定义当需要用户登录时候，转到的登录页面
                .and()
                .httpBasic();
    }

}